package com.baizhi.controller;

import com.baizhi.annotation.LogAnnotation;
import com.baizhi.entity.Article;
import com.baizhi.service.ArticleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.Map;

@RestController
@RequestMapping("/article")
public class ArticleController {
    @Autowired
    private ArticleService articleService;

    //展示所有数据并进行分页
    @RequestMapping("/selectAll")
    @LogAnnotation(value = "展示全部文章",type = "selectAll")
    public Map selectAll(int page,int limit,String articleName){
        return articleService.selectAll(page, limit, articleName);
    }

    //根据ID查找一条数据
    @RequestMapping("/selectOne")
    @LogAnnotation(value = "展示单条文章",type = "selectOne")
    public Article selectOne(int id){
        return articleService.selectOne(id);
    }

    //增加一个数据
    @RequestMapping("/insert")
    @LogAnnotation(value = "添加文章",type = "insert")
    public Map insert(Article article,MultipartFile file,HttpServletRequest request) throws IOException {
        //做重命名，放置文件同名被覆盖
        String realPath = request.getServletContext().getRealPath("/img/article");//绝对路径
        String newFilename=new Date().getTime()+"_"+file.getOriginalFilename();
        file.transferTo(new File(realPath+"/"+newFilename));
        article.setArticleImage("/img/article/"+newFilename);
        return articleService.insert(article);
    }


    //删除一条数据
    @RequestMapping("/delete")
    @LogAnnotation(value = "删除一条文章",type = "delete")
    public Map delete(int id){
        return articleService.delete(id);
    }

    //修改一条数据
    @RequestMapping("/update")
    @LogAnnotation(value = "更新文章",type = "update")
    public Map update(Article article, MultipartFile file, HttpServletRequest request) throws IOException {

        if(file!=null){
            //做重命名，放置文件同名被覆盖
            String realPath = request.getServletContext().getRealPath("/img/article");//绝对路径
            String newFilename=new Date().getTime()+"_"+file.getOriginalFilename();
            file.transferTo(new File(realPath+"/"+newFilename));
            article.setArticleImage("/img/article/"+newFilename);
            return articleService.update(article);
        }else{
            return articleService.updatea(article);
        }

    }
   //批量下载
    @RequestMapping("/download")
    @LogAnnotation(value="导出文章数据",type = "download")
    public Map selectAlls(){
        return articleService.selectAlls();
    }


}
